<?php

namespace App\Http\Controllers\Api;

use App\BalanceRecord;
use App\Banner;
use App\Button;
use App\Classify;
use App\DiscountSalesRule;
use App\DiscountXMedicine;
use App\DistributionOrder;
use App\Enterprise;
use App\Exceptions\OrderException;
use App\FictitiouShopCart;
use App\HelperShopCart;
use App\Http\Services\CommonManager;
use App\Http\Services\DomainManager;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\MedicineSnapshot;
use App\Merchant;
use App\MerchantDeliveryMethod;
use App\MerchantMedicine;
use App\MerchantMedicineArea;
use App\MerchantMedicineXArea;
use App\MerchantMedicineXClassify;
use App\Message;
use App\OrderAddress;
use App\OrderItem;
use App\Orders;
use App\PrescriptionDisease;
use App\PrescriptionInfo;
use App\PrescriptionInfoImgs;
use App\RechargeRule;
use App\ShopCart;
use App\SystemMedicine;
use App\User;
use App\UserAddress;
use App\UserCoupon;
use App\UserDrug;
use DB;
use Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class MallController extends Controller
{
    /**@author cmj
     * 获取店铺列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMerchantList(Request $request){
        $lat    =$request->input('lat')   ?? 0;
        $lng    =$request->input('lng')   ?? 0;
        $page   =$request->input('page')  ?? 1;
        $limit  =$request->input('limit') ?? 8;
        $merchant_id  = $request->input('merchant_id');
        $area_id  = $request->input('area_id');
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;

        $enterpriseId=1;

        $merchants = Merchant::whereStatus(1)->whereReview(1);
        $merchants = $merchants->whereEnterpriseId($enterpriseId);

        if(!is_null($area_id) && $area_id != 0){
            $merchantIds = MerchantMedicineXArea::whereMerchantMedicineAreaId($area_id)->pluck("merchant_medicine_id")->toArray();
            $merchants = $merchants->whereIn("id",$merchantIds);
        }
        //屏蔽其他商家
        if ($merchant_id)
            $merchants = $merchants->whereId($merchant_id);
        //添加测试数据
        if ($merchants->count()==0){
            $merchants=Merchant::whereId(42);
            $page_info['total']=1;
        } else {
            $page_info['total']=$merchants->count();
        }

        $allPoint =$merchants->get();
        $sort_array=[];
        if (count($allPoint) > 0){
            foreach ($allPoint as $item){
                $tmpDistance=ToolsManager::getDistance($lng,$lat,$item->lng,$item->lat);
                $temp=[
                    'distance'      =>$tmpDistance ?? '',
                    'merchant_id'   =>$item->id,
                    'name'          =>$item->name,
                    'desc'          =>$item->desc,
                    'province'      =>$item->province,
                    'city'          =>$item->city,
                    'area'          =>$item->area,
                    'address'       =>$item->address,
                    'contact'       =>$item->contact,
                    'lng'           =>$item->lng,
                    'lat'           =>$item->lat,
                    'business_time' =>$item->business_time,
                    'business_start_time' => $item->business_start_time,
                    'business_end_time' => $item->business_end_time,
                    'support_delivery_method'=>$item->support_delivery_method ? json_decode($item->support_delivery_method) : ['待确定'],
                    'status'        =>$item->status,
                    'logo_img_id'   =>$item->logo_img_id,
                    'logo_img_url'  =>FileManager::getImgUrl($item->logo_img_id),
                ];
                array_push($sort_array,$temp);
            }
        }
        asort($sort_array);
        $data=array_slice($sort_array,$page * $limit,$limit);
        if (count($data) > 0){
            foreach ($data as $item){
                $item['logo_img_url']=FileManager::getImgUrl($item['logo_img_id']);
            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$data,'page_info'=>$page_info]);
    }

    /**@author cmj
     * 获取店铺列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMerchantInfo(Request $request){
        $merchant_id  = $request->input('merchant_id');
        $enterpriseId = 1;

        $merchants = Merchant::whereStatus(1)->whereReview(1);
        $merchants = $merchants->whereEnterpriseId($enterpriseId);
        //屏蔽其他商家
        if ($merchant_id)
            $merchants = $merchants->whereId($merchant_id);

        $item =$merchants->first();

                $temp=[
                    'distance'      =>$tmpDistance ?? '',
                    'merchant_id'   =>$item->id,
                    'name'          =>$item->name,
                    'desc'          =>$item->desc,
                    'province'      =>$item->province,
                    'city'          =>$item->city,
                    'area'          =>$item->area,
                    'address'       =>$item->address,
                    'contact'       =>$item->contact,
                    'lng'           =>$item->lng,
                    'lat'           =>$item->lat,
                    'business_time' =>$item->business_time,
                    'business_start_time' => $item->business_start_time,
                    'business_end_time' => $item->business_end_time,
                    'support_delivery_method'=>$item->support_delivery_method ? json_decode($item->support_delivery_method) : ['待确定'],
                    'status'        =>$item->status,
                    'logo_img_id'   =>$item->logo_img_id,
                    'logo_img_url'  =>FileManager::getImgUrl($item->logo_img_id),
                    'bg_url'        =>$item->bg_url
                ];


        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$temp]);
    }

    /**@author cmj
     * 获取首页banner轮播图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIndexBannerList(Request $request){
        $enterpriseId=1;

        $merchant_id=1;

        $banners=Banner::getIndexBanner();
        return response()->json(['level'=>'success','message'=>'success','data'=>$banners]);
    }

    /**@author cmj
     * 获取功能区按钮列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIndexButtonList(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $merchant_id = 1;

//        if (!Enterprise::isEnterpriseMerchant($enterpriseId,$merchant_id))
//            return response()->json(['level'=>'error','message'=>'店铺不存在']);

        $button=Button::getIndexFunctionButton();
        return response()->json(['level'=>'success','message'=>'success','data'=>$button]);
    }

    /**@author cmj
     * 获取首页专区列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIndexAreaList(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $merchant_id = 10;

        if (!Enterprise::isEnterpriseMerchant($enterpriseId,$merchant_id))
            return response()->json(['level'=>'error','message'=>'店铺不存在']);

        $areas=MerchantMedicineArea::getIndexSpecialArea($merchant_id);
        if(count($areas) > 0){
            foreach ($areas as $area){
                $thatMerchantIds = MerchantMedicineXArea::whereMerchantMedicineAreaId($area->id)->pluck("merchant_medicine_id")->toArray();
                $thatMerchants = Merchant::whereIn("id",$thatMerchantIds)->get();
                if(count($thatMerchants) > 0){
                    foreach ($thatMerchants as $thatMerchant){
                        $thatMerchant->logo_img_url = FileManager::getImgUrl($thatMerchant->logo_img_id);
                    }
                }

                $area->merchant_list = $thatMerchants;
            }
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$areas]);
    }

    /**@author cmj
     * 获取销售的分类列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBuyingClassifyList(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $merchant_id=$request->input('merchant_id') ?? 0;

        if (!Enterprise::isEnterpriseMerchant($enterpriseId,$merchant_id))
            return response()->json(['level'=>'error','message'=>'店铺不存在']);

        $data=Classify::getBuyingClassifyList($merchant_id);
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$data]);
    }

    /**@author cmj
     * 获取药品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMerchantMedicineList(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $merchant_id=$request->input('merchant_id') ?? 0;
        $area_id    =$request->input('area_id')     ?? 0;
        $classify_id=$request->input('classify_id') ?? 0;
        $page       =$request->input('page')        ?? 1;
        $limit      =$request->input('limit')       ?? 8;
        $keyword    =$request->input('keyword')     ?? '';
        $ref        =$request->input('ref','');
        $page_info=[
            'page'=>$page,
            'limit'=>$limit,
        ];

//        if($ref == 'udesk'){
//            $merchant = Merchant::whereId($merchant_id)->first();
//            if(!$merchant)
//                return response()->json(['level' => 'error','message' => '店铺不存在']);
//        }else{
//            if (!Enterprise::isEnterpriseMerchant($enterpriseId,$merchant_id))
//                return response()->json(['level'=>'error','message'=>'店铺不存在']);
//        }

        $page=$page-1;
        if(!is_null($merchant_id) && $merchant_id != 0)
            $data=MerchantMedicine::whereMerchantId($merchant_id)->whereIsShop(1);
        else
            $data=MerchantMedicine::whereIsShop(1);

        if ($area_id){
            $medicine_ids=MerchantMedicineXArea::whereMerchantMedicineAreaId($area_id)
                ->pluck('merchant_medicine_id')
                ->toArray();
            $data=$data->whereIn('id',$medicine_ids);
        }
        if ($classify_id){
            $medicine_ids=MerchantMedicineXClassify::whereClassifyId($classify_id)
                ->pluck('merchant_medicine_id')
                ->toArray();
            $data=$data->whereIn('id',$medicine_ids);
        }

        if($keyword != ''){
            $data=$data->where('name','like','%'.trim($keyword).'%');
        }
        $page_info['total']=$data->count();
        $data=$data->orderBy('sort','asc')
            ->orderBy('id','desc')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            /** @var MerchantMedicine $item */
            foreach ($data as $item){
                $item->thumb_url=MerchantMedicine::getMerchantMedicineImg($item->id);
            }
        }
        $result=[
            'medicine_info'=>$data,
            'area_info'=>MerchantMedicineArea::getAreaInfo($area_id),
            'classify_info'=>Classify::getClassifyInfo($classify_id)
        ];
//        $data=MerchantMedicine::getMerchantMedicineList($merchant_id,$page,$limit,$area_id);
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$result,'page_info'=>$page_info]);
    }

    /**@author cmj
     * 获取药品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMedicineDetail(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $medicine_id=$request->input('medicine_id') ?? 0;
        $merchant_id=$request->input('merchant_id') ?? 0;
        $ref        =$request->input('ref','');


//        if($ref == 'udesk'){
//            $merchant = Merchant::whereId($merchant_id)->first();
//            if(!$merchant)
//                return response()->json(['level' => 'error','message' => '店铺不存在']);
//        }else{
//            if (!Enterprise::isEnterpriseMerchant($enterpriseId,$merchant_id))
//                return response()->json(['level'=>'error','message'=>'店铺不存在']);
//        }

        $data=MerchantMedicine::getMedicineDetailInfo($medicine_id);
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$data]);
    }

    public function getRecommendRecord(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $wxOpenid = $request->input('wx_openid','');

        /** @var User $user */
        $user = User::whereWxOpenid($wxOpenid)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit  = $request->input('limit') ?? 3;
        $page   = $request->input('page') ?? 1;
        $agentPhoneNumber = $request->input('agent_phone_number','');
        $merchant_id      = $request->input('merchant_id') ?? 0;

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page -= 1;

        $merchant = Merchant::whereId($merchant_id)->first();
        if(!$merchant)
            return response()->json(['level' => 'error','message' => '店铺不存在']);

        $thisMerchant  = Merchant::whereId($merchant_id)->first() ?? (object)['id'=>$merchant_id,'name'=>'无店铺信息'];

        $data = [];
        $thisMerchantMedicines  = FictitiouShopCart::whereUserId($user->id)
            ->whereMerchantId($merchant_id)
            ->where('agent_phone_number',$agentPhoneNumber)
            ->select('key')
            ->groupBy('key')
            ->get();
        if(count($thisMerchantMedicines) > 0){
            foreach ($thisMerchantMedicines as $thisMerchantMedic) {
                $fictitiouShopCartList = FictitiouShopCart::whereUserId($user->id)
                    ->whereMerchantId($merchant_id)
                    ->where('agent_phone_number',$agentPhoneNumber)
                    ->where('key',$thisMerchantMedic->key)
                    ->get();
                if (count($fictitiouShopCartList) > 0){
                    foreach ($fictitiouShopCartList as $fictitiouShopCart){
                        $fictitiouShopCart->medicine_info=MerchantMedicine::getMedicineListItemInfo($fictitiouShopCart->merchant_medicine_id);
                    }
                }

                $temp=[
                    'merchant_id'=>$thisMerchant ? $thisMerchant->id : 0,
                    'name'=>$thisMerchant ? $thisMerchant->name : '无数据',
                    'cart_item'=>$fictitiouShopCartList
                ];

                array_push($data,$temp);
            }
        }

        $page_info['total'] = count($data);
        $thisPageIds=array_slice($data,$page * $limit,$limit);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisPageIds,'page_info' => $page_info]);
    }

    public function getFictitiousShopCart(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $wxOpenid = $request->input('wx_openid','');

        /** @var User $user */
        $user = User::whereWxOpenid($wxOpenid)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit  = $request->input('limit') ?? 3;
        $page   = $request->input('page') ?? 1;
        $merchant_id      = $request->input('merchant_id') ?? 0;
        $agentPhoneNumber = $request->input('agent_phone_number','');
        $key              = $request->input('key','');
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page -= 1;

        $data = [];

        if($merchant_id != 0){
            $merchant = Merchant::whereId($merchant_id)->first();
            if(!$merchant)
                return response()->json(['level' => 'error','message' => '店铺不存在']);

            $thisMerchant  = Merchant::whereId($merchant_id)->first() ?? (object)['id'=>$merchant_id,'name'=>'无店铺信息'];

            $thisMerchantMedicines  = FictitiouShopCart::whereUserId($user->id)
                ->whereMerchantId($merchant_id);

            if($key != ''){
                $thisMerchantMedicines = $thisMerchantMedicines->where('key',$key);
            }

            if($agentPhoneNumber != ''){
                $thisMerchantMedicines = $thisMerchantMedicines->where('agent_phone_number',$agentPhoneNumber);
            }

            $page_info['total'] = $thisMerchantMedicines->count();

            $thisMerchantMedicines = $thisMerchantMedicines->offset($page * $limit)->limit($limit)->get();

            if (count($thisMerchantMedicines) > 0){
                foreach ($thisMerchantMedicines as $thisMerchantMedicine){
                    $thisMerchantMedicine->medicine_info=MerchantMedicine::getMedicineListItemInfo($thisMerchantMedicine->merchant_medicine_id);
                }
            }
            $temp=[
                'merchant_id'=>$thisMerchant ? $thisMerchant->id : 0,
                'name'=>$thisMerchant ? $thisMerchant->name : '无数据',
                'cart_item'=>$thisMerchantMedicines
            ];

            array_push($data,$temp);
        } else {
            /** @var ShopCart $shopCart */
            $shopCartMerchantIds = FictitiouShopCart::whereUserId($user->id);
            if($agentPhoneNumber != '') {
                $shopCartMerchantIds = $shopCartMerchantIds->where('agent_phone_number',$agentPhoneNumber);
            }

            if($key != ''){
                $shopCartMerchantIds = $shopCartMerchantIds->where('key',$key);
            }

            $shopCartMerchantIds = $shopCartMerchantIds->whereEnterpriseId($enterpriseId)
                ->orderBy('id','desc')
                ->pluck('merchant_id')
                ->toArray();

            $Ids=array_unique($shopCartMerchantIds);
            $page_info['total']=count($Ids);

            if (count($Ids)>0){
                $thisPageIds=array_slice($Ids,$page * $limit,$limit);
                if (count($thisPageIds) > 0){
                    foreach ($thisPageIds as $item){
                        $thisMerchant           =Merchant::whereId($item)->first() ?? (object)['id'=>$item,'name'=>'无店铺信息'];
                        $thisMerchantMedicines  =FictitiouShopCart::whereUserId($user->id);

                        if($agentPhoneNumber != '') {
                            $thisMerchantMedicines = $thisMerchantMedicines->where('agent_phone_number',$agentPhoneNumber);
                        }

                        if($key != ''){
                            $thisMerchantMedicines = $thisMerchantMedicines->where('key',$key);
                         }

                        $thisMerchantMedicines = $thisMerchantMedicines->whereMerchantId($item)
                            ->get();
                        if (count($thisMerchantMedicines) > 0){
                            foreach ($thisMerchantMedicines as $thisMerchantMedicine){
                                $thisMerchantMedicine->medicine_info=MerchantMedicine::getMedicineListItemInfo($thisMerchantMedicine->merchant_medicine_id);
                            }
                        }
                        $temp=[
                            'merchant_id'=>$thisMerchant ? $thisMerchant->id : 0,
                            'name'=>$thisMerchant ? $thisMerchant->name : '无数据',
                            'cart_item'=>$thisMerchantMedicines
                        ];
                        array_push($data,$temp);
                    }
                }
            }

        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data,'page_info'=>$page_info]);
    }

    public function getHelperShopCart(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $wxOpenid = $request->input('wx_openid','');

        /** @var User $user */
        $user = User::whereWxOpenid($wxOpenid)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit  = $request->input('limit') ?? 3;
        $page   = $request->input('page') ?? 1;
        $merchant_id   = $request->input('merchant_id') ?? 0;
        $agentPhoneNumber = $request->input('agent_phone_number','');
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page   = $page - 1;
        $data=[];
        if ($merchant_id){
            $merchant = Merchant::whereId($merchant_id)->first();
            if(!$merchant)
                return response()->json(['level' => 'error','message' => '店铺不存在']);

            $thisMerchant           = Merchant::whereId($merchant_id)->first() ?? (object)['id'=>$merchant_id,'name'=>'无店铺信息'];

            $medicineIds=MerchantMedicine::whereIsShop(1)->whereMerchantId($merchant_id)->pluck('id')->toArray();

            $thisMerchantMedicines  = HelperShopCart::whereUserId($user->id)
                ->whereMerchantId($merchant_id)
                ->whereIn('merchant_medicine_id',$medicineIds);

            if($agentPhoneNumber != ''){
                $thisMerchantMedicines = $thisMerchantMedicines->where('agent_phone_number',$agentPhoneNumber);
            }

            $page_info['total'] = $thisMerchantMedicines->count();

            $thisMerchantMedicines = $thisMerchantMedicines->get();

            if (count($thisMerchantMedicines) > 0){
                foreach ($thisMerchantMedicines as $thisMerchantMedicine){
                    $thisMerchantMedicine->medicine_info=MerchantMedicine::getMedicineListItemInfo($thisMerchantMedicine->merchant_medicine_id);
                }
            }
            $temp=[
                'merchant_id'=>$thisMerchant ? $thisMerchant->id : 0,
                'name'=>$thisMerchant ? $thisMerchant->name : '无数据',
                'cart_item'=>$thisMerchantMedicines
            ];
            array_push($data,$temp);
        } else {
            if($agentPhoneNumber != '') {
                /** @var ShopCart $shopCart */
                $shopCartMerchantIds = HelperShopCart::whereUserId($user->id)
                    ->where('agent_phone_number',$agentPhoneNumber)
                    ->whereEnterpriseId($enterpriseId)
                    ->orderBy('id','desc')
                    ->pluck('merchant_id')
                    ->toArray();
            }else{
                /** @var ShopCart $shopCart */
                $shopCartMerchantIds = HelperShopCart::whereUserId($user->id)
                    ->whereEnterpriseId($enterpriseId)
                    ->orderBy('id','desc')
                    ->pluck('merchant_id')
                    ->toArray();
            }

            $Ids=array_unique($shopCartMerchantIds);
            $page_info['total']=count($Ids);

            if (count($Ids)>0){
                $thisPageIds=array_slice($Ids,$page * $limit,$limit);
                if (count($thisPageIds) > 0){
                    foreach ($thisPageIds as $item){
                        $thisMerchant           =Merchant::whereId($item)->first() ?? (object)['id'=>$item,'name'=>'无店铺信息'];
                        if($agentPhoneNumber != '') {
                            $thisMerchantMedicines  =HelperShopCart::whereUserId($user->id)
                                ->where('agent_phone_number',$agentPhoneNumber)
                                ->whereMerchantId($item)
                                ->get();
                        }else{
                            $thisMerchantMedicines  =HelperShopCart::whereUserId($user->id)
                                ->whereMerchantId($item)
                                ->get();
                        }

                        if (count($thisMerchantMedicines) > 0){
                            foreach ($thisMerchantMedicines as $thisMerchantMedicine){
                                $thisMerchantMedicine->medicine_info=MerchantMedicine::getMedicineListItemInfo($thisMerchantMedicine->merchant_medicine_id);
                            }
                        }
                        $temp=[
                            'merchant_id'=>$thisMerchant ? $thisMerchant->id : 0,
                            'name'=>$thisMerchant ? $thisMerchant->name : '无数据',
                            'cart_item'=>$thisMerchantMedicines
                        ];
                        array_push($data,$temp);
                    }
                }
            }

        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data,'page_info'=>$page_info]);
    }

    public function addHelperShopCart(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $wxOpenid = $request->input('wx_openid','');

        /** @var User $user */
        $user = User::whereWxOpenid($wxOpenid)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $medicine_id  = $request->input('medicine_id')    ?? 0;
        $num          = $request->input('num')            ?? 0;
        $change       = $request->input('change')         ?? 0;
        $agentPhoneNumber   = $request->input('agent_phone_number','');
        $agentEmail         = $request->input('agent_email','');


        $thisMedicine = MerchantMedicine::whereId($medicine_id)->whereIsShop(1)->first();
        if(!$thisMedicine)
            return response()->json(['level' => 'error','message' => '该商品已下架','data'=>[]]);

//        if (!in_array($thisMedicine->merchant_id,Enterprise::getEnterpriseMerchantIds($enterpriseId)))
//            return response()->json(['level'=>'error','message'=>'该药品不存在','data'=>[]]);

        $merchant = Merchant::whereId($thisMedicine->merchant_id)->first();

        $shopCart = HelperShopCart::whereUserId($user->id)
            ->whereMerchantMedicineId($thisMedicine->id)
            ->whereMerchantId($thisMedicine->merchant_id)
            ->where('agent_phone_number',$agentPhoneNumber)
            ->first();

        if(!$shopCart){
            $shopCart= new HelperShopCart();
            $shopCart->user_id      = $user->id;
            $shopCart->unit_price   = $thisMedicine->selling_price;
            $shopCart->merchant_medicine_id = $thisMedicine->id;
            $shopCart->merchant_id  = $thisMedicine->merchant_id;
            $shopCart->enterprise_id = $merchant ? $merchant->enterprise_id : 0;
            $shopCart->agent_phone_number = $agentPhoneNumber;
            $shopCart->agent_email        = $agentEmail;
        }
        if ($num)    $shopCart->num = $num;
        if ($change) $shopCart->num = $shopCart->num + $change;

        if ($shopCart->num<=0)
            return response()->json(['level'=>'error','message'=>'不能再减了']);

        if($thisMedicine->stock < $shopCart->num || $thisMedicine->stock == 0)
            return response()->json(['level' => 'error','message' => '商品库存不足']);

        $shopCart->save();
        return response()->json(['level' => 'success','message' => '加入购物车成功','data' => $shopCart]);
    }

    public function deleteHelperShopCart(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $wxOpenid = $request->input('wx_openid','');

        /** @var User $user */
        $user = User::whereWxOpenid($wxOpenid)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $shopCartIds = $request->input('shop_cart_ids');
        $merchant_id = $request->input('merchant_id');

        if(is_array($shopCartIds))
            HelperShopCart::whereUserId($user->id)
                ->whereIn('id', $shopCartIds)
                ->delete();

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    public function choiceMedicine(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $wxOpenid         = $request->input('wx_openid','');
        $shop_cart_ids    = $request->get('shop_cart_ids') ?? 0;

        /** @var User $user */
        $user = User::whereWxOpenid($wxOpenid)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        if (is_array($shop_cart_ids) && count($shop_cart_ids) > 0) {
            $key = md5(time() . rand(10000,99999));

            /**开始处理优惠*/
            $allCartMedicine = HelperShopCart::whereUserId($user->id)
                ->whereIn('id', $shop_cart_ids)->get();
            if (count($allCartMedicine) > 0) {
                foreach ($allCartMedicine as $cart) {
                    $shopCart= new FictitiouShopCart();
                    $shopCart->user_id      = $cart->user_id;
                    $shopCart->unit_price   = $cart->unit_price;
                    $shopCart->merchant_medicine_id = $cart->merchant_medicine_id;
                    $shopCart->merchant_id  = $cart->merchant_id;
                    $shopCart->enterprise_id  = $cart->enterprise_id;
                    $shopCart->num            = $cart->num;
                    $shopCart->agent_phone_number = $cart->agent_phone_number;
                    $shopCart->agent_email = $cart->agent_email;
                    $shopCart->key = $key;
                    $shopCart->save();
                }
            }
        }else{
            return response()->json(['level' => 'error','message' => '参数错误']);
        }

        return response()->json(['level' => 'success','message' => '操作成功','data' => $key]);
    }

    /**@author cmj
     * 添加购物车接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws Exception
     */
    public function addShopCart(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $medicine_id  = $request->input('medicine_id')    ?? 0;
        $num          = $request->input('num')            ?? 0;
        $change       = $request->input('change')         ?? 0;

        $thisMedicine = MerchantMedicine::whereId($medicine_id)->whereIsShop(1)->first();
        if(!$thisMedicine)
            return response()->json(['level' => 'error','message' => '该商品已下架','data'=>[]]);

        if (!in_array($thisMedicine->merchant_id,Enterprise::getEnterpriseMerchantIds($enterpriseId)))
            return response()->json(['level'=>'error','message'=>'该药品不存在','data'=>[]]);

        $shopCart = ShopCart::whereUserId($user->id)
            ->whereMerchantMedicineId($thisMedicine->id)
            ->whereMerchantId($thisMedicine->merchant_id)
            ->whereEnterpriseId($enterpriseId)
            ->first();

        if(!$shopCart){
            $shopCart= new ShopCart();
            $shopCart->user_id      = $user->id;
            $shopCart->unit_price   = $thisMedicine->selling_price;
            $shopCart->merchant_medicine_id = $thisMedicine->id;
            $shopCart->merchant_id  = $thisMedicine->merchant_id;
            $shopCart->enterprise_id  = $enterpriseId;
        }
        if ($num)    $shopCart->num = $num;
        if ($change) $shopCart->num = $shopCart->num + $change;

        if ($shopCart->num<=0)
            return response()->json(['level'=>'error','message'=>'不能再减了']);

        if($thisMedicine->stock < $shopCart->num || $thisMedicine->stock == 0)
            return response()->json(['level' => 'error','message' => '商品库存不足']);

        $shopCart->save();
        return response()->json(['level' => 'success','message' => '加入购物车成功','data' => $shopCart]);
    }

    /**
     * 获取购物车列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShopCart(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit  = $request->input('limit') ?? 3;
        $page   = $request->input('page') ?? 1;
        $merchant_id   = $request->input('merchant_id') ?? 0;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page   = $page - 1;
        $data=[];
//        if ($merchant_id){
////            if (!Enterprise::isEnterpriseMerchant($enterpriseId,$merchant_id))
////                return response()->json(['level'=>'error','message'=>'店铺不存在']);
//
//            $thisMerchant           = Merchant::whereId($merchant_id)->first() ?? (object)['id'=>$merchant_id,'name'=>'无店铺信息'];
//            $thisMerchantMedicines  = ShopCart::whereUserId($user->id)
//                ->whereEnterpriseId($enterpriseId)
//                ->get();
//            $page_info['total']     = ShopCart::whereUserId($user->id)
//                ->whereMerchantId($merchant_id)
//                ->whereEnterpriseId($enterpriseId)
//                ->count();
//            if (count($thisMerchantMedicines) > 0){
//                foreach ($thisMerchantMedicines as $thisMerchantMedicine){
//                    $thisMerchantMedicine->medicine_info=MerchantMedicine::getMedicineListItemInfo($thisMerchantMedicine->merchant_medicine_id);
//                }
//            }
//            $temp=[
//                'merchant_id'=>$thisMerchant ? $thisMerchant->id : 0,
//                'name'=>$thisMerchant ? $thisMerchant->name : '无数据',
//                'cart_item'=>$thisMerchantMedicines
//            ];
//            array_push($data,$temp);
//        } else {
            /** @var ShopCart $shopCart */
            $shopCartMerchantIds = ShopCart::whereUserId($user->id)
                ->whereEnterpriseId($enterpriseId)
                ->orderBy('id','desc')
                ->pluck('merchant_id')
                ->toArray();
            $Ids=array_unique($shopCartMerchantIds);
            $page_info['total']=count($Ids);

            if (count($Ids)>0){
                $thisPageIds=array_slice($Ids,$page * $limit,$limit);
                if (count($thisPageIds) > 0){
                    foreach ($thisPageIds as $item){
                        $thisMerchant           =Merchant::whereId($item)->first() ?? (object)['id'=>$item,'name'=>'无店铺信息'];
                        $thisMerchantMedicines  =ShopCart::whereUserId($user->id)
                            ->whereMerchantId($item)
                            ->get();
                        if (count($thisMerchantMedicines) > 0){
                            foreach ($thisMerchantMedicines as $thisMerchantMedicine){
                                $thisMerchantMedicine->medicine_info=MerchantMedicine::getMedicineListItemInfo($thisMerchantMedicine->merchant_medicine_id);
                            }
                        }
                        $temp=[
                            'merchant_id'=>$thisMerchant ? $thisMerchant->id : 0,
                            'name'=>$thisMerchant ? $thisMerchant->name : '无数据',
                            'cart_item'=>$thisMerchantMedicines
                        ];
                        array_push($data,$temp);
                    }
                }
            }

//        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data,'page_info'=>$page_info]);
    }

    /**
     * 删除购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws Exception
     */
    public function deleteShopCart(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $shopCartIds = $request->input('shop_cart_ids');
        $merchant_id = $request->input('merchant_id');

        if(is_array($shopCartIds))
            ShopCart::whereUserId($user->id)
                ->whereEnterpriseId($enterpriseId)
                ->whereIn('id', $shopCartIds)
                ->delete();
        if ($merchant_id)
            ShopCart::whereUserId($user->id)->whereMerchantId($merchant_id)->delete();
        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    /**@author cmj
     * 搜索药品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchMedicine(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $keyword    =$request->input('keyword')     ?? '';
        $page       =$request->input('page')        ?? 1;
        $limit      =$request->input('limit')       ?? 8;
        $merchantId =$request->input('merchant_id') ?? 8;

        $page_info=[
            'page'=>$page,
            'limit'=>$limit,
        ];
        $page=$page-1;
        if (!trim($keyword))
            return response()->json(['level'=>'error','message'=>'请输入搜索词','data'=>[]]);
        $data=MerchantMedicine::whereIsShop(1)->whereMerchantId($merchantId)
//            ->whereIn('merchant_id',Enterprise::getEnterpriseMerchantIds($enterpriseId))
            ->where('name','like','%'.trim($keyword).'%');
        $page_info['total']=$data->count();
        $data=$data->offset($page * $limit)->limit($limit)->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->merchant_name=Merchant::getMerchantName($item->merchant_id);
                $item->thumb_url= merchantMedicine::getMerchantMedicineImg($item->id);

            }
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$data,'page_info'=>$page_info]);
    }

    public function buildOrder(Request $request){
        $enterpriseId=1;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $medicine_id=$request->input('medicine_id') ?? 0;
        $shop_cart_ids=$request->input('shop_cart_ids') ?? 0;
        $num        =$request->input('num') ?? 1;

        $remark     =$request->input('remark') ?? '';
//        $coupon_id   =$request->input('coupon_id') ?? 0;
        $address_id  =$request->input('address_id') ?? 0;
        $delivery_method  =$request->input('delivery_method') ?? '';
        $phone  =$request->input('phone') ?? '';
        $couponId = $request->get('coupon_id') ?? 0;
        $agentPhoneNumber   = $request->input('agent_phone_number','');
        $agentEmail         = $request->input('agent_email','');

        $prescriptionOrder   = $request->input('prescription_order') ?? 0;
        $userDrugId          = $request->input('user_drug_id') ?? 0;
        $hasPrescription     = $request->input('has_prescription') ?? 0;
        $diseaseInfo         = $request->input('disease_info') ?? [];
        $diagnoseDescription = $request->input('diagnose_description');
        $prescriptionImgs    = $request->input('prescription_imgs') ?? [];
        $diagnosticLevel     = $request->input('diagnostic_level') ?? 0;
        $drugUsage           = $request->input('drug_usage') ?? 0;
        $payWay              = $request->input('pay_way') ?? 'wechatpay';

        if (!in_array($delivery_method,['express_delivery','self_pick','instant_delivery']))
            return response()->json(['level'=>'error','message'=>'请选择收货方式']);
        if ($delivery_method!='self_pick'){
            $thisAddress    =UserAddress::whereUserId($user->id)->whereId($address_id)->first();
            if (!$thisAddress)
                return response()->json(['level'=>'error','message'=>'地址选择错误，请重新选择地址']);
        } else {
            if (!$phone)
                return response()->json(['level'=>'error','message'=>'请输入联系手机号']);
        }

        if($prescriptionOrder == 1){
            $userDrug = UserDrug::whereUserId($user->id)->whereId($userDrugId)->first();
            if(!$userDrug)
                return response()->json(['level' => 'error','message' => '用药人不存在']);

            if($hasPrescription == 1){
                if(!is_array($prescriptionImgs) || (is_array($prescriptionImgs) && count($prescriptionImgs) <= 0))
                    return response()->json(['level' => 'error','message' => '请上传处方图片']);
            }else{
                if(!is_array($diseaseInfo) || (is_array($diseaseInfo) && count($diseaseInfo) <= 0))
                    return response()->json(['level' => 'error','message' => '请选择疾病']);

                if(empty($diagnoseDescription))
                    return response()->json(['level' => 'error','message' => '请填写病症描述']);

                if(empty($diagnosticLevel))
                    return response()->json(['level' => 'error','message' => '请选择诊断级别']);

                if(empty($drugUsage))
                    return response()->json(['level' => 'error','message' => '请选择既往用药情况']);
            }
        }

        //TODO 配送费用
        $delivery_fee=0;

        /** 创建单号 */
        $orderNum = ToolsManager::makeBillNum();
        while(true){
            $isOrders = Orders::whereOrderNum($orderNum)->first();
            if($isOrders){
                $orderNum = ToolsManager::makeBillNum();
            }else{
                break;
            }
        }

        try{
           DB::beginTransaction();
           /** @var MerchantMedicine $thisMedicine */
           $thisMedicine=MerchantMedicine::whereId($medicine_id)->lockForUpdate()->first();
           /** 直接购买 */
           if ($medicine_id && $thisMedicine){
               if ($num > $thisMedicine->stock){
                   $result=['success'=>false,'message'=>'库存不足'];
                   DB::rollBack();
               } else {
                   //TODO 创建快照
                   $snapshotId=self::buildMedicineSnapshot($thisMedicine);
                   $delivery_setting=MerchantDeliveryMethod::whereMerchantId($thisMedicine->merchant_id)
                       ->whereDeliveryMethod($delivery_method)
                       ->first();
                   $delivery_fee=$delivery_setting ? $delivery_setting->delivery_fee : 0;
                   if ($delivery_method=='self_pick'){
                       $orderAddress=new OrderAddress();
                       $orderAddress->user_id=$user->id;
                       $orderAddress->phone  =$phone ?? '';
                       $orderAddress->save();
                       $orderAddressId=$orderAddress->id;
                   } else {
                       //TODO 创建订单地址
                       $orderAddressId=self::buildOrderAddress($address_id);
                   }


                   //TODO 创建订单
                   $order=new Orders();
                   $order->pay_way = $payWay;
                   $order->order_num=$orderNum;
                   $order->user_id=$user->id;
                   $order->merchant_id=$thisMedicine->merchant_id;
                   $order->enterprise_id=$enterpriseId;
                   $order->order_address_id=$orderAddressId;
                   $order->original_price=0;
                   $order->discount_price=0;
                   $order->discount_name='';
                   $order->coupon_id=0;
                   $order->coupon_reduce_price=0;
                   $order->pay_amount=0;
                   $order->delivery_method=$delivery_method;
                   $order->delivery_fee=$delivery_fee;
//                       $order->express_time=;
//                       $order->delivery_method=;
                   $order->remark=$remark ?? '';
                   $order->status=1;
                   $order->save();

                   //TODO 满减
                   $total_amount    =round($thisMedicine->selling_price * $num,2);
                   $reduce_amount   =round(DiscountXMedicine::getGoodsReducePrice($thisMedicine->id,$total_amount),2);
                   $order->original_price=$total_amount;
                   $order->discount_price=$total_amount;
                   if ($reduce_amount > 0){
                       $order->discount_price=$total_amount - $reduce_amount;
                       $order->discount_name=DiscountXMedicine::getGoodsReduceName($thisMedicine->id,$total_amount);
                   }

                    //TODO 优惠券使用
                   $couponAmount = 0;
                   if($couponId != 0) {
                       /** @var UserCoupon $userCoupon */
                       $userCoupon = UserCoupon::whereCouponId($couponId)->whereIsLocking(0)->whereIsUse(0)->whereUserId($user->id)->where('end_time','>',date("Y-m-d H:i:s"))->first();
                       if($userCoupon){
                           $couponAmount=$userCoupon->money;
                           if($userCoupon->type == 'satisfy' && $order->discount_price < $userCoupon->satisfy_money){
                               $couponAmount = 0;
                           }


                           $userCoupon->is_locking=1;
                           $userCoupon->save();
                           $order->coupon_id=$userCoupon->id;
                           $order->save();
                       }
                   }

                   $order->coupon_reduce_price = $couponAmount;
                   $payAmount = $order->discount_price + $delivery_fee - $couponAmount;
                   if($payAmount < 0){
                       $payAmount = 0;
                   }
                   $order->pay_amount=$payAmount;
                   $order->save();
                   // ToDo 子订单
                   $newOrderItem = new OrderItem();
                   $newOrderItem->order_id      = $order->id;
                   $newOrderItem->merchant_medicine_id= $thisMedicine->id;
                   //TODO 存SPU
                   $newOrderItem->item_num      = $order->order_num. '#' . rand(1000,9999);
                   $newOrderItem->original_price= round($thisMedicine->selling_price,2);
                   $newOrderItem->num           = $num;
                   $newOrderItem->total_amount  = round($total_amount-$reduce_amount,2);
                   $newOrderItem->discount_price= round($newOrderItem->total_amount / $num,2);
                   $newOrderItem->goods_snapshot_id = $snapshotId;
                   $newOrderItem->save();
                   //减库存
                   $thisMedicine->stock=$thisMedicine->stock - $num;
                   $thisMedicine->save();

                   if($order->pay_amount <= 0){
                       $order->is_pay = 1;
                       $order->pay_time = date("Y-m-d H:i:s",time());
                       $order->status = 2;
                       $order->save();

                       if($couponId != 0) {
                           $userCoupon->is_use = 1;
                           $userCoupon->save();
                       }

                       $userInfo = CommonManager::getUserBasicInfo($order->user_id);
                       $nickname = $userInfo ? $userInfo['nickname'] : '';

                       $newMessage = new Message();
                       $newMessage->user_id       = $order->user_id;
                       $newMessage->enterprise_id = $order->enterprise_id;
                       $newMessage->merchant_id   = $order->merchant_id;
                       $newMessage->order_num     = $order->order_num;
                       $newMessage->content       = $nickname . '有一个待发货的订单';
                       $newMessage->save();
                   }
                   DB::commit();
                   $result=['success'=>true,'message'=>'下单成功'];
               }
           } else if (is_array($shop_cart_ids) && count($shop_cart_ids) > 0){

               if ($delivery_method=='self_pick'){
                   $orderAddress=new OrderAddress();
                   $orderAddress->user_id=$user->id;
                   $orderAddress->phone  =$phone ?? '';
                   $orderAddress->save();
                   $orderAddressId=$orderAddress->id;
               } else {
                   /** 购物车购买 */
                   //TODO 创建订单地址
                   $orderAddressId=self::buildOrderAddress($address_id);
               }


               //TODO 创建订单
               $order=new Orders();
               $order->pay_way = $payWay;
               $order->order_num=$orderNum;
               $order->user_id=$user->id;
//               $order->merchant_id=$thisMedicine->merchant_id;
               $order->order_address_id=$orderAddressId;
               $order->delivery_method=$delivery_method;
//               $order->delivery_fee=$delivery_fee;
//                       $order->original_price=;
//                       $order->discount_price=;
//                       $order->discount_name=;
//                       $order->coupon_id=;
//                       $order->coupon_reduce_price=;
//                       $order->pay_amount=;
//                       $order->express_time=;
//                       $order->delivery_method=;
               $order->remark=$remark ?? '';
               $order->agent_phone_number = $agentPhoneNumber;
               $order->agent_email = $agentEmail;
               $order->status=1;
               $order->save();


               $medicineRuleMoney=[];
               $medicineRuleSatisfy=[];
               $satisfyRuleId=[];
               $allReduce=0;
               if (count($shop_cart_ids) > 0){
                   /**开始处理优惠*/
                   $allCartMedicine=ShopCart::whereUserId($user->id)
                       ->whereEnterpriseId($enterpriseId)
                       ->whereIn('id',$shop_cart_ids)
                       ->get();
                   $merchantIds=Enterprise::getEnterpriseMerchantIds($enterpriseId);
                   if (count($allCartMedicine) > 0){
                       foreach ($allCartMedicine as $cart){
                           if ($order->merchant_id==0){
                               $order->merchant_id  =$cart->merchant_id;
                               $order->enterprise_id=$enterpriseId;
                               $delivery_setting=MerchantDeliveryMethod::whereMerchantId($order->merchant_id)
                                   ->whereDeliveryMethod($delivery_method)
                                   ->first();
                               $delivery_fee=$delivery_setting ? $delivery_setting->delivery_fee : 0;
                           }
                           if (!in_array($cart->merchant_id,$merchantIds)){
                               DB::rollBack();
                               return response()->json(['level'=>'error','message'=>'有商品不属于此域名']);
                           }


                           if ($order->merchant_id !=$cart->merchant_id){
                               DB::rollBack();
                               return response()->json(['level'=>'error','message'=>'一次只能结算一家店铺哦']);
                           }

                           $allRules=DiscountXMedicine::getGoodsRuleIds($cart->merchant_medicine_id);
                           $thisMPrice=MerchantMedicine::getSellingPrice($cart->merchant_medicine_id);
                           $thisMSumPrice=$thisMPrice * $cart->num;
                           if (count($allRules) > 0){
                               //统计各商品参加的促销活动以及参加各促销活动的商品累计金额
                               foreach ($allRules as $ruleId=>$satisfyMoney){
                                   if (!isset($medicineRuleMoney[$ruleId])){
                                       $medicineRuleMoney[$ruleId] = round($thisMSumPrice,2);
                                   } else {
                                       $temp=$medicineRuleMoney[$ruleId];
                                       $medicineRuleMoney[$ruleId] = round($temp + $thisMSumPrice,2);
                                   }

                                   if (!isset($medicineRuleSatisfy[$ruleId])){
                                       $medicineRuleSatisfy[$ruleId] = round($satisfyMoney,2);
                                   }
                               }
                           }
                       }
                       if (count($medicineRuleSatisfy) > 0){
                           //按活动满足的金额排序
                           arsort($medicineRuleSatisfy);
                           foreach ($medicineRuleSatisfy as $ruleId=>$satisfy){
                               $temp=$medicineRuleMoney[$ruleId];
                               if ($temp >= $satisfy){
                                   $allReduce=$allReduce + DiscountSalesRule::getRuleReduceMoney($ruleId);
                                   array_push($satisfyRuleId,$ruleId);
                               }
                           }
                       }

                   } else {
                       DB::rollBack();
                       return response()->json(['level'=>'error','message'=>'你选择的购物车商铺不存在']);
                   }
                   /** 结束处理优惠 */

                   $total_amount=0;
                   /**
                    * 开始处理订单*/
                   //TODO 满减
                   if ($allReduce > 0){
                       if (count($satisfyRuleId) > 0){
                           foreach ($satisfyRuleId as $rule_id) {
                               if ($order->discount_name == '')
                                   $order->discount_name = DiscountSalesRule::getRuleName($rule_id);
                               else
                                   $order->discount_name = ($order->discount_name) . ',' . DiscountSalesRule::getRuleName($rule_id);
                           }
                       }

                   }

                   foreach ($shop_cart_ids as $cart_id){
                       $thisCart=ShopCart::whereId($cart_id)
                           ->whereUserId($user->id)
                           ->whereEnterpriseId($enterpriseId)
                           ->first();
                       if ($thisCart){
                           /** @var MerchantMedicine $thisMedicine */
                           $thisMedicine=MerchantMedicine::whereId($thisCart->merchant_medicine_id)->lockForUpdate()->first();
                           if ($thisMedicine) {
                               if ($thisCart->num > $thisMedicine->stock) {
                                   $result = ['success' => false, 'message' => '库存不足'];
                                   DB::rollBack();
                               } else {
                                   //TODO 创建快照
                                   $snapshotId = self::buildMedicineSnapshot($thisMedicine);
                                   $thisMtotalAmount = round($thisMedicine->selling_price * $thisCart->num,2);
                                   // ToDo 子订单
                                   $newOrderItem = new OrderItem();
                                   $newOrderItem->order_id      = $order->id;
                                   $newOrderItem->merchant_medicine_id= $thisMedicine->id;
                                   //TODO 存SPU
                                   $newOrderItem->item_num      = $order->order_num. '#' . rand(1000,9999);
                                   $newOrderItem->original_price= $thisMedicine->selling_price;
                                   $newOrderItem->discount_price= $thisMedicine->selling_price;
                                   $newOrderItem->num           = $thisCart->num;
                                   $newOrderItem->total_amount  = $thisMtotalAmount;
                                   $newOrderItem->goods_snapshot_id = $snapshotId;
                                   if($thisCart->agent_phone_number)
                                        $newOrderItem->agent_phone_number = $thisCart->agent_phone_number;
                                   if($thisCart->agent_email)
                                       $newOrderItem->agent_email = $thisCart->agent_email;
                                   $newOrderItem->save();
                                   $total_amount=$total_amount + $newOrderItem->total_amount;
                                   //减库存
                                   $thisMedicine->stock=$thisMedicine->stock - $thisCart->num;
                                   $thisMedicine->save();
                               }
                           }
                           $thisCart->delete();
                       }
                   }
                   $order->original_price   = $total_amount;
                   $order->discount_price   = $total_amount-$allReduce;
                   $order->delivery_fee     = $delivery_fee;

                   //TODO 优惠券使用
                   $couponAmount = 0;
                   if($couponId != 0) {
                       /** @var UserCoupon $userCoupon */
                       $userCoupon = UserCoupon::whereCouponId($couponId)->whereIsLocking(0)->whereIsUse(0)->whereUserId($user->id)->where('end_time','>',date("Y-m-d H:i:s"))->first();
                       if($userCoupon){
                           $couponAmount=$userCoupon->money;
                           if($userCoupon->type == 'satisfy' && $order->discount_price < $userCoupon->satisfy_money){
                               $couponAmount = 0;
                           }


                           $userCoupon->is_locking=1;
                           $userCoupon->save();
                           $order->coupon_id=$userCoupon->id;
                           $order->save();
                       }
                   }
                   $order->coupon_reduce_price = $couponAmount;
                   $payAmount = $order->discount_price + $delivery_fee - $couponAmount;
                   if($payAmount < 0){
                       $payAmount = 0;
                   }
                   $order->pay_amount=$payAmount;
                   $order->save();

                   if($order->pay_amount <= 0){
                       $order->is_pay = 1;
                       $order->pay_time = date("Y-m-d H:i:s",time());
                       $order->status = 2;
                       if ($order->delivery_method == 'self_pick')
                           $order->status=3;
                       $order->save();

                       if($couponId != 0) {
                           $userCoupon->is_use = 1;
                           $userCoupon->save();
                       }

                       $userInfo = CommonManager::getUserBasicInfo($order->user_id);
                       $nickname = $userInfo ? $userInfo['nickname'] : '';

                       $newMessage = new Message();
                       $newMessage->user_id       = $order->user_id;
                       $newMessage->enterprise_id = $order->enterprise_id;
                       $newMessage->merchant_id   = $order->merchant_id;
                       $newMessage->order_num     = $order->order_num;
                       $newMessage->content       = $nickname . '有一个待发货的订单';
                       $newMessage->save();
                   }
                   DB::commit();
                   $result=['success'=>true,'message'=>'下单成功'];
               }
               else {
                   $result=['success'=>false,'message'=>'请选择需要结算商品'];
               }


           } else {
               $result=['success'=>false,'message'=>'下单参数错误'];
           }

           if($prescriptionOrder == 1 && $order){
                self::buildPrescriptionInfo($userDrugId,$enterpriseId,$order,$hasPrescription,$diseaseInfo,$diagnoseDescription,$prescriptionImgs,$diagnosticLevel,$drugUsage);
           }

       } catch (Exception $e){
           DB::rollBack();
           \Log::error($e->getTraceAsString());
           return response()->json(['level'=>'error','message'=>'下单错误，错误信息：'.$e->getMessage()]);
       }
       if ($result['success']){
           if($order->pay_amount <= 0){
               return response()->json(['level' => 'paying','message' => '支付成功','data' => $order]);
           }

           //加入分销订单
           DistributionOrder::addDistributionOrder($order->id,$order->order_num,$order->pay_amount,$order->user_id);

           return response()->json(['level'=>'success','message'=>'下单成功','data'=>$order]);
       } else {
           return response()->json(['level'=>'error','message'=>$result['message'],'data'=>[]]);
       }
    }
    public function submitOrder(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $medicine_id=$request->get('medicine_id') ?? 0;
        $shop_cart_ids=$request->get('shop_cart_ids') ?? 0;
        $num        =$request->get('num') ?? 1;
        $address_id  =$request->get('address_id') ?? 0;
        $delivery_method  =$request->get('delivery_method') ?? '';
        $couponId = $request->get('coupon_id') ?? 0;

        if($couponId != 0){
            /** @var UserCoupon $thisUserCoupon */
            $thisUserCoupon = UserCoupon::whereCouponId($couponId)->whereUserId($user->id)->first();
            if(!$thisUserCoupon)
                return response()->json(['level' => 'error','message' => '您没有该优惠券!']);

            if($thisUserCoupon->is_use == 1)
                return response()->json(['level' => 'error','message' => '该优惠券已使用']);

            if(strtotime($thisUserCoupon->end_time) <= time())
                return response()->json(['level' => 'error','message' => '该优惠券已过期']);

            if($thisUserCoupon->is_locking == 1)
                return response()->json(['level' => 'error','message' => '优惠券已被锁定']);
        }

//        $thisMedicine   =MerchantMedicine::whereId($medicine_id)->first();

//        if (in_array($delivery_method,['instant_delivery','express_delivery'])) {
//            $thisAddress = UserAddress::whereUserId($user->id)->whereId($address_id)->first();
//            if (!$thisAddress)
//                return response()->json(['level' => 'error', 'message' => '地址选择错误，请重新选择地址']);
//        }
//        if (!$thisMedicine)
//            return response()->json(['level'=>'error','message'=>'该药品不存在','data'=>[]]);
        $delivery_fee=0;
           /** @var MerchantMedicine $thisMedicine */
           $thisMedicine=MerchantMedicine::whereId($medicine_id)->first();
           /** 直接购买 */
           if ($medicine_id && $thisMedicine) {
               if ($num > $thisMedicine->stock)
                   return response()->json(['level' => 'error', 'message' => '库存不足', 'data' => []]);
               //TODO 满减
               $total_amount = round($thisMedicine->selling_price * $num, 2);
               $reduce_amount = round(DiscountXMedicine::getGoodsReducePrice($thisMedicine->id, $total_amount), 2);
               $data = [];
               $data['notice']     = '';
               if ($delivery_method !='self_extract'){
                   $thisAddress = UserAddress::whereUserId($user->id)->whereId($address_id)->first();
                    if($thisAddress){
                        $delivery_setting=MerchantDeliveryMethod::whereMerchantId($thisMedicine->merchant_id)
                            ->whereDeliveryMethod($delivery_method)
                            ->first();
                        $thisMerchant=Merchant::whereId($thisMedicine->merchant_id)->first();
                        if ($delivery_setting){
                            $delivery_fee=$delivery_setting ? $delivery_setting->delivery_fee : 0;
                            if ($delivery_setting->delivery_range && $delivery_method == 'instant_delivery'){
                                //$thisAddress->province.$thisAddress->city.$thisAddress->area.$thisAddress->address,
                                $range=ToolsManager::getDistanceByAddress(
                                    $thisAddress->province.$thisAddress->city.$thisAddress->area.$thisAddress->address,
                                    $thisMerchant->lng ?? 0,
                                    $thisMerchant->lat ?? 0);
                                $distance = round($range/1000,2);
                                if ($distance > ($delivery_setting->delivery_range + 0.10))
                                    $data['notice']     = "距离：$distance 千米，最大配送距离：$delivery_setting->delivery_range 千米";
                            }
                        }
                    }

               }

               $data['original_price'] = $total_amount;
               $data['discount_price'] = $total_amount;
               $data['delivery_fee']   = round($delivery_fee,2);
               $data['reduce_amount']  = $reduce_amount;
               if ($reduce_amount > 0) {
//                   $data['discount_price'] = round($total_amount - $data['delivery_fee'],2) ;
                   $data['discount_price'] = round($total_amount - $reduce_amount,2) ;
                   $data['discount_name'] = DiscountXMedicine::getGoodsReduceName($thisMedicine->id, $total_amount);
               }

               $data['coupon_money'] = 0;
               if($couponId != 0){
                   if($thisUserCoupon->type == 'satisfy' && $thisUserCoupon->satisfy_money <= $data['discount_price']){
                       $data['coupon_money'] = $thisUserCoupon->money;
                   }elseif($thisUserCoupon->type == 'direct'){
                       $data['coupon_money'] = $thisUserCoupon->money;
                   }else{
                       return response()->json(['level' => 'error','message' => '未达到优惠券使用要求']);
                   }
               }

               $data['pay_amount'] = round($data['discount_price'] + $delivery_fee - $data['coupon_money'],2);
               if($data['pay_amount'] < 0){
                   $data['pay_amount'] = 0.00;
               }
               $data['goods_info'] = [MerchantMedicine::getMedicineListItemInfo($thisMedicine->id,$num)];
               return response()->json(['level' => 'success', 'message' => '预览成功', 'data' => $data]);
           } else if (is_array($shop_cart_ids)) {
               /** 购物车购买 */
               $data=[];
               $data['goods_info'] =[];
               $data['notice']     = '';
               $medicineRuleMoney = [];
               $medicineRuleSatisfy = [];
               $satisfyRuleId = [];
               $allReduce = 0;
               if (count($shop_cart_ids) > 0) {
                   /**开始处理优惠*/
                   $allCartMedicine = ShopCart::whereUserId($user->id)
                       ->whereEnterpriseId($enterpriseId)
                       ->whereIn('id', $shop_cart_ids)->get();
                   if (count($allCartMedicine) > 0) {
                       $merchant=0;
                       foreach ($allCartMedicine as $cart) {
                           if ($merchant==0){
                               $merchant=$cart->merchant_id;
                               if ($delivery_method !='self_extract'){
                                   $thisAddress = UserAddress::whereUserId($user->id)->whereId($address_id)->first();
                                    if($thisAddress){
                                        $delivery_setting=MerchantDeliveryMethod::whereMerchantId($cart->merchant_id)
                                            ->whereDeliveryMethod($delivery_method)
                                            ->first();
                                        $thisMerchant=Merchant::whereId($cart->merchant_id)->first();
                                        if ($delivery_setting){
                                            $delivery_fee=$delivery_setting ? $delivery_setting->delivery_fee : 0;
                                            if ($delivery_setting->delivery_range && $delivery_method == 'instant_delivery'){
                                                $range=ToolsManager::getDistanceByAddress(
                                                    $thisAddress->province.$thisAddress->city.$thisAddress->area.$thisAddress->address,
                                                    $thisMerchant->lng ?? 0,
                                                    $thisMerchant->lat ?? 0);
                                                if (round($range/1000,2) > $delivery_setting->delivery_range)
                                                    $data['notice']     = "距离：$range 米，设置：$delivery_setting->delivery_range 千米";
                                            }
                                        }
                                    }
                               }
                           }

                           if ($merchant!=$cart->merchant_id)
                               return response()->json(['level'=>'error','message'=>'一次只能结算一家店铺哦']);
                           $allRules = DiscountXMedicine::getGoodsRuleIds($cart->merchant_medicine_id);
                           $thisMPrice = MerchantMedicine::getSellingPrice($cart->merchant_medicine_id);
                           $thisMSumPrice = $thisMPrice * $cart->num;
                           if (count($allRules) > 0) {
                               //统计各商品参加的促销活动以及参加各促销活动的商品累计金额
                               foreach ($allRules as $ruleId => $satisfyMoney) {
                                   if (!isset($medicineRuleMoney[$ruleId])) {
                                       $medicineRuleMoney[$ruleId] = round($thisMSumPrice, 2);
                                   } else {
                                       $temp = $medicineRuleMoney[$ruleId];
                                       $medicineRuleMoney[$ruleId] = round($temp + $thisMSumPrice, 2);
                                   }

                                   if (!isset($medicineRuleSatisfy[$ruleId])) {
                                       $medicineRuleSatisfy[$ruleId] = round($satisfyMoney, 2);
                                   }
                               }
                           }
                       }
                       if (count($medicineRuleSatisfy) > 0) {
                           //按活动满足的金额排序
                           arsort($medicineRuleSatisfy);
                           foreach ($medicineRuleSatisfy as $ruleId => $satisfy) {
                               $temp = $medicineRuleMoney[$ruleId];
                               if ($temp >= $satisfy) {
                                   $allReduce = $allReduce + DiscountSalesRule::getRuleReduceMoney($ruleId);
                                   array_push($satisfyRuleId, $ruleId);
                               }
                           }
                       }

                   } else {
                       return response()->json(['level'=>'error','message'=>'你选择的商品不存在']);
                   }
                   /** 结束处理优惠 */

                   $total_amount = 0;
                   /**
                    * 开始处理订单*/
                   //TODO 满减
                   if ($allReduce > 0) {
                       if (count($satisfyRuleId) > 0) {
                           foreach ($satisfyRuleId as $rule_id) {
                               if (!isset($data['discount_name']))
                                   $data['discount_name'] = DiscountSalesRule::getRuleName($rule_id);
                               else
                                   $data['discount_name'] = ($data['discount_name']) . ',' . DiscountSalesRule::getRuleName($rule_id);
                           }
                       }

                   }

                   foreach ($shop_cart_ids as $cart_id) {
                       $thisCart = ShopCart::whereId($cart_id)
                           ->whereEnterpriseId($enterpriseId)
                           ->whereUserId($user->id)->first();
                       if ($thisCart) {
                           /** @var MerchantMedicine $thisMedicine */
                           $thisMedicine = MerchantMedicine::whereId($thisCart->merchant_medicine_id)->lockForUpdate()->first();
                           if ($thisMedicine) {
                               if ($thisCart->num > $thisMedicine->stock)
                                   return response()->json(['level' => 'error', 'message' => '库存不足', 'data' => []]);

                               $thisMtotalAmount = round($thisMedicine->selling_price * $thisCart->num, 2);

                               $total_amount = $total_amount + $thisMtotalAmount;
                               array_push($data['goods_info'],MerchantMedicine::getMedicineListItemInfo($thisCart->merchant_medicine_id,$thisCart->num));
                           }
                       }
                   }

                   $data['delivery_fee']   = round($delivery_fee,2);
                   $data['original_price'] = round($total_amount,2);
                   $data['discount_price'] = round($total_amount - $allReduce,2);
                   $data['reduce_amount']  = $allReduce;

                   $data['coupon_money'] = 0;
                   if($couponId != 0){
                       if($thisUserCoupon->type == 'satisfy' && $thisUserCoupon->satisfy_money <= $data['discount_price']){
                           $data['coupon_money'] = $thisUserCoupon->money;
                       }elseif($thisUserCoupon->type == 'direct'){
                           $data['coupon_money'] = $thisUserCoupon->money;
                       }else{
                           return response()->json(['level' => 'error','message' => '未达到优惠券使用要求']);
                       }
                   }

                   $data['pay_amount']     = round($data['discount_price'] + $data['delivery_fee'] - $data['coupon_money'],2);
                   if($data['pay_amount'] < 0){
                       $data['pay_amount'] = 0.00;
                   }
                   return response()->json(['level' => 'success', 'message' => '预览成功', 'data' => $data]);
               }
           } else {
               return response()->json(['level' => 'error', 'message' => '参数错误', 'data' => []]);
           }
    }

    public function helperShopCartChange(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $shop_cart_ids      = $request->get('shop_cart_ids') ?? 0;
        $wxOpenid           = $request->input('wx_openid','');

        /** @var User $user */
        $user = User::whereWxOpenid($wxOpenid)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);


        $shopCartIds = [];
        $pharmacistInfo = [
            'agent_phone_number' => '',
            'agent_email' => ''
        ];

        if (is_array($shop_cart_ids) && count($shop_cart_ids) > 0) {
              /**开始处理优惠*/
              $allCartMedicine = FictitiouShopCart::whereUserId($user->id)
                  ->whereEnterpriseId($enterpriseId)
                  ->whereIn('id', $shop_cart_ids)->get();
              if (count($allCartMedicine) > 0) {
                  foreach ($allCartMedicine as $cart) {
                      if(empty($pharmacistInfo['agent_phone_number'])){
                          $pharmacistInfo['agent_phone_number'] = $cart->agent_phone_number;
                      }

                      if(empty($pharmacistInfo['agent_email'])){
                          $pharmacistInfo['agent_email'] = $cart->agent_email;
                      }

                      $shopCart = ShopCart::whereUserId($cart->user_id)
                          ->whereMerchantMedicineId($cart->merchant_medicine_id)
                          ->whereMerchantId($cart->merchant_id)
                          ->whereEnterpriseId($cart->enterprise_id)
                          ->first();

                      if(!$shopCart){
                          $shopCart= new ShopCart();
                          $shopCart->user_id      = $cart->user_id;
                          $shopCart->unit_price   = $cart->unit_price;
                          $shopCart->merchant_medicine_id = $cart->merchant_medicine_id;
                          $shopCart->merchant_id  = $cart->merchant_id;
                          $shopCart->enterprise_id  = $cart->enterprise_id;
                          $shopCart->num            = $cart->num;
                          $shopCart->save();
                      }else{
//                          if($cart->num > $shopCart->num){
                              $shopCart->num = $cart->num;
                              $shopCart->save();
//                          }
                      }

                      array_push($shopCartIds,$shopCart->id);
                  }
              }
          }else{
            return response()->json(['level' => 'error','message' => '参数错误']);
          }

          return response()->json(['level' => 'success','message' => '操作成功','data' => $shopCartIds,'pharmacist_info' => $pharmacistInfo]);
    }

    public function getMerchantSupportDeliveryMethod(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $merchant_id=$request->input('merchant_id') ?? 0;

        if (!Enterprise::isEnterpriseMerchant($enterpriseId,$merchant_id))
            return response()->json(['level'=>'error','message'=>'店铺不存在']);

        $data=Merchant::getMerchantSupportDeliveryMethod($merchant_id);
        return response()->json(['level'=>'success','message'=>'success','data'=>$data]);
    }

    public function getDiseaseList(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $medicineName = $request->input('medicine_name') ?? '';
        $medicineSpace = $request->input('medicine_space') ?? '';

        $diseaseList = PaymentController::getDrugListByTradeName($medicineName,$medicineSpace);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $diseaseList]);
    }

    public function searchDiseaseList(Request $request){
        $enterpriseId=1;;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $diseaseName = $request->input('disease_name') ?? '';
        $page = $request->input('page') ?? 1;
        $limit = $request->input('limit') ?? 10;

        if(empty($diseaseName))
            return response()->json(['level' => 'error','message' => '请填写疾病名称搜索条件']);

        $diseaseList = PaymentController::getAllDiseaseList($diseaseName,$page,$limit);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $diseaseList]);
    }

    public static function buildPrescriptionInfo($userDrugId = 0,$enterprise_id = 0,Orders $order = null,$hasPrescription = 1,$diseaseInfo = [],$diagnoseDescription = '',$prescriptionImgs = [],$diagnosticLevel = 1,$drugUsage = 1){
        if(empty($userDrugId) || empty($order))
            return null;

        $newPrescriptionInfo = new PrescriptionInfo();
        $newPrescriptionInfo->user_drug_id        = $userDrugId;
        $newPrescriptionInfo->enterprise_id       = $enterprise_id;
        $newPrescriptionInfo->has_prescription    = $hasPrescription;
        $newPrescriptionInfo->diagnoseDescription = $diagnoseDescription;
        $newPrescriptionInfo->diagnosticLevel     = $diagnosticLevel;
        $newPrescriptionInfo->drugUsage           = $drugUsage;
        $newPrescriptionInfo->save();

        if(is_array($diseaseInfo) && count($diseaseInfo) > 0){
            foreach ($diseaseInfo as $disease) {
                $id = $disease['id'];
                $name = $disease['name'];

                $newPrescriptionDiseases = new PrescriptionDisease();
                $newPrescriptionDiseases->prescription_info_id = $newPrescriptionInfo->id;
                $newPrescriptionDiseases->disease_id   = $id;
                $newPrescriptionDiseases->disease_name = $name;
                $newPrescriptionDiseases->save();
            }
        }

        if(is_array($prescriptionImgs) && count($prescriptionImgs) > 0){
            foreach ($prescriptionImgs as $prescriptionImg) {
                $newPrescriptionInfoImg = new PrescriptionInfoImgs();
                $newPrescriptionInfoImg->prescription_info_id = $newPrescriptionInfo->id;
                $newPrescriptionInfoImg->img_id               = $prescriptionImg;
                $newPrescriptionInfoImg->save();
            }
        }

        $order->prescription_info_id = $newPrescriptionInfo->id;
        $order->save();
    }

    private static function buildMedicineSnapshot(MerchantMedicine $thisMedicine){
        $snapshot= new MedicineSnapshot();
        $snapshot->merchant_medicine_id =$thisMedicine->id;
        $snapshot->merchant_id          =$thisMedicine->merchant_id ?? 0;
        $snapshot->name                 =$thisMedicine->name ?? '';
        $snapshot->desc                 =$thisMedicine->desc ?? '';
        $snapshot->upc                  =$thisMedicine->upc ?? '';
        $snapshot->sku_ssn              =$thisMedicine->sku_ssn ?? '';
        $snapshot->approval_number      =$thisMedicine->approval_number ?? '';
        $snapshot->specification        =$thisMedicine->specification ?? '';
        $snapshot->thumb_id             =$thisMedicine->thumb_id ?? 0;
        $snapshot->selling_price        =$thisMedicine->selling_price ?? 0;
        $snapshot->stock                =$thisMedicine->stock ?? 0;
        $snapshot->classify_id          =$thisMedicine->classify_id ?? 0;
        $snapshot->manufacturer         =$thisMedicine->manufacturer ?? '';
        $snapshot->manufacturer_address =$thisMedicine->manufacturer_address ?? '';
        $snapshot->manufacturer_contact =$thisMedicine->manufacturer_contact ?? '';
        $snapshot->electronic_regulatory_code=$thisMedicine->electronic_regulatory_code ?? '';
        $snapshot->usage_and_dosage     =$thisMedicine->usage_and_dosage ?? '';
        $snapshot->indications          =$thisMedicine->indications ?? '';
        $snapshot->adapt_to_the_crowd   =$thisMedicine->adapt_to_the_crowd ?? '';
        $snapshot->component            =$thisMedicine->component ?? '';
        $snapshot->adverse_reactions    =$thisMedicine->adverse_reactions ?? '';
        $snapshot->contraindications    =$thisMedicine->contraindications ?? '';
        $snapshot->precautions          =$thisMedicine->precautions ?? '';
        $snapshot->interaction          =$thisMedicine->interaction ?? '';
        $snapshot->medication_for_children=$thisMedicine->medication_for_children ?? '';
        $snapshot->medication_for_pregnancy_x_lactation=$thisMedicine->medication_for_pregnancy_x_lactation ?? '';
        $snapshot->medication_for_aged  =$thisMedicine->medication_for_aged ?? '';
        $snapshot->properties           =$thisMedicine->properties ?? '';
        $snapshot->packing              =$thisMedicine->packing ?? '';
        $snapshot->dosage_form          =$thisMedicine->dosage_form ?? '';
        $snapshot->storage              =$thisMedicine->storage ?? '';
        $snapshot->pharmacological_action=$thisMedicine->pharmacological_action ?? '';
        $snapshot->expiry_date          =$thisMedicine->expiry_date ?? '';
        $snapshot->detail               =$thisMedicine->detail ?? '';
        $snapshot->other_attribute_array=$thisMedicine->other_attribute_array ?? '';
        $snapshot->save();
        return $snapshot->id ?? 0;
    }
    private static function buildOrderAddress($user_address_id){
        $thisAddress=UserAddress::whereId($user_address_id)->first();
        if ($thisAddress){
            $orderAddress=new OrderAddress();
            $orderAddress->user_id=$thisAddress->user_id;
            $orderAddress->consignee=$thisAddress->consignee;
            $orderAddress->province=$thisAddress->province;
            $orderAddress->city=$thisAddress->city;
            $orderAddress->area=$thisAddress->area;
            $orderAddress->address=$thisAddress->address;
//            $orderAddress->postcode=$thisAddress->postcode;
            $orderAddress->phone=$thisAddress->phone;
            $orderAddress->floor=$thisAddress->floor;
            $orderAddress->has_lift=$thisAddress->has_lift;
            $orderAddress->save();
            return $orderAddress->id ?? 0;
        }
        return 0;
    }

    public static function getDeliveryName($delivery_method){
        if ($delivery_method == 'express_delivery')
            return '快递';
        if ($delivery_method == 'self_pick')
            return '自提';
        if ($delivery_method == 'instant_delivery')
            return '即时配送';
        return $delivery_method;
    }

    /**
     * 生成充值记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function buildRechargeOrder(Request $request) {
        $enterpriseId=1;
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $rechargeRuleId = $request->input('recharge_rule_id') ?? 0;

        $rechargeRule = RechargeRule::whereId($rechargeRuleId)->first();
        if (!$rechargeRule) {
            return response()->json(['level' => 'error', 'message' => '请选择充值金额']);
        }

        if ($rechargeRule->recharge_amount < 0.01) {
            return response()->json(['level' => 'error', 'message' => '充值金额有误']);
        }

        $orderNum = ToolsManager::makeRechargeNum();
        while (true) {
            $is_exist = BalanceRecord::whereOrderNum($orderNum)->first();
            if($is_exist) {
                $orderNum = ToolsManager::makeRechargeNum();
            } else {
                break;
            }
        }

        $thatRecord = new BalanceRecord();
        $thatRecord->order_num = $orderNum;
        $thatRecord->user_id = $user->id;
        $thatRecord->type = 0;
        $thatRecord->recharge_amount = $rechargeRule->recharge_amount;
        $thatRecord->status = 0;
        $thatRecord->is_pay = 0;
        $thatRecord->pay_way = 'wechatpay';
        $thatRecord->save();

        return response()->json(['level' => 'success', 'message' => '下单成功', 'data' => $thatRecord]);
    }

    public function getShopsClassify(Request $request){
        $allClassifys = Classify::whereType("merchant")->whereStatus(1)->orderBy("sort","asc")->get();

        return response()->json(['level' => 'success', 'message' => '获取成功', 'data' => $allClassifys]);
    }
}
